import { io, Socket } from 'socket.io-client';
import { API_CONFIG } from '../config/api';

class SocketService {
  private socket: Socket | null = null;
  private token: string | null = null;

  connect(token: string) {
    this.token = token;
    
    this.socket = io(API_CONFIG.BASE_URL.replace('/api', ''), {
      auth: {
        token: this.token
      }
    });

    this.socket.on('connect', () => {
      console.log('Connected to server');
    });

    this.socket.on('disconnect', () => {
      console.log('Disconnected from server');
    });

    this.socket.on('connect_error', (error) => {
      console.error('Connection error:', error);
    });

    return this.socket;
  }

  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
  }

  // 设备状态监听
  onDeviceStatusChanged(callback: (data: any) => void) {
    this.socket?.on('device_status_changed', callback);
  }

  // 安全警报监听
  onSecurityAlert(callback: (data: any) => void) {
    this.socket?.on('new_security_alert', callback);
  }

  // 人员位置监听
  onPersonnelLocationChanged(callback: (data: any) => void) {
    this.socket?.on('personnel_location_changed', callback);
  }

  // 停车状态监听
  onParkingStatusChanged(callback: (data: any) => void) {
    this.socket?.on('parking_status_changed', callback);
  }

  // 系统心跳监听
  onSystemHeartbeat(callback: (data: any) => void) {
    this.socket?.on('system_heartbeat', callback);
  }

  // 发送事件
  emitDeviceStatusUpdate(data: any) {
    this.socket?.emit('device_status_update', data);
  }

  emitSecurityAlert(data: any) {
    this.socket?.emit('security_alert', data);
  }

  emitLocationUpdate(data: any) {
    this.socket?.emit('location_update', data);
  }

  emitParkingStatusUpdate(data: any) {
    this.socket?.emit('parking_status_update', data);
  }

  // 移除监听器
  off(event: string, callback?: Function) {
    this.socket?.off(event, callback);
  }
}

export const socketService = new SocketService();